package com.zym.utils.EasyExcel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.zym.entity.User;
import com.zym.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class UserDataListener extends AnalysisEventListener<User> {
    private static final Logger log = LoggerFactory.getLogger(UserDataListener.class);

    /**
     * 每10000条存储一次数据库
     */
    private static final int BATCH_COUNT = 10000;
    private  int successCount = 0;
    private  List<User> list = new ArrayList<>();
    private  List<User> failList = new ArrayList<>();

    private UserService userService;

    private AtomicInteger count = new AtomicInteger();

    public int getSuccessCount() {
        return successCount;
    }

    public void setSuccessCount(int successCount) {
        this.successCount = successCount;
    }

    public List<User> getList() {
        return list;
    }

    public void setList(List<User> list) {
        this.list = list;
    }

    public List<User> getFailList() {
        return failList;
    }

    public void setFailList(List<User> failList) {
        this.failList = failList;
    }

    public UserDataListener(UserService userService) {
        this.userService = userService;
    }
    public UserDataListener() {

    }
    @Override
    public void invoke(User user, AnalysisContext context) {
        String errMsg;
        try {
            //数据验证
            errMsg = ExcelValidateHelper.validateEntity(user);
            //byDb
            //.....
        } catch (NoSuchFieldException e) {
            errMsg = "解析数据出错";
            log.error("解析数据出错：" + e.getMessage());
        }

        if (StringUtils.isBlank(errMsg)) {
            list.add(user);
        } else {
            failList.add(user);
            log.error("解析数据出错：" + errMsg);
        }

        if (list.size() >= BATCH_COUNT) {
            saveData(true);
            successCount += list.size();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (list.size() > 0) {
            saveData(false);
            successCount += list.size();
            list.clear();
        }

        log.info("所有数据解析完成！");
        log.info("导入成功：{}条数据", successCount);
        log.info("导入失败：{}条数据", failList.size());
    }

    /**
     * 保存至数据库
     */
    private void saveData(boolean isNotLastBatch) {
        log.info("第{}次{}条数据，开始写入数据库！", count.incrementAndGet(), list.size());
        //byMybatis
        userService.saveBatch(list);

        //byJdbc
        log.info("写入数据库成功！");
    }


}
